import generate from '@babel/generator';
import * as t from '@babel/types';

import { ITypeEntity, ITypeEntityField } from '@/types/modules/superType/types';
import { transformFieldValue } from '@/types/modules/superType/utils/transformValue';
import { getFileLocalPath } from '@/types/modules/superType/utils/get-file-local-path';
import { getTypeById, getTypeByParams } from '@/utils/editor-adapter/editorResource';
const logger = (arg: any, ...x) => {};
let voTypes = [];

/**
 * 生成 ITypeEntity 元数据注释 (JSDoc 格式)
 */
function generateTypeEntityMetaComment(typeEntity: ITypeEntity): string {
  const lines = [`/**`];

  // 主描述（使用 desc）
  if (typeEntity.desc) {
    lines.push(` * ${typeEntity.desc}`);
  }

  // 详细介绍
  if (typeEntity.intro) {
    lines.push(` * ${typeEntity.intro}`);
  }

  lines.push(` */`);
  return lines.join('\n');
}

// 生成 TypeORM 装饰器
const generateTypeOrmDecorator = (field: ITypeEntityField, dbType?: string) => {
  const decorators = [];

  if (field.db) {
    // 处理主键
    if (field.db.isPrimary) {
      if (field.db.isGenerated) {
        decorators.push(t.decorator(t.callExpression(t.identifier('PrimaryGeneratedColumn'), [])));
      } else {
        decorators.push(t.decorator(t.callExpression(t.identifier('PrimaryColumn'), [])));
      }
      return decorators;
    }

    const columnOptions: any = {};

    // 处理字段类型
    if (field.db.type) {
      // 根据数据库类型转换字段类型
      switch (dbType) {
        case 'postgres':
          // PostgreSQL 特定类型
          if (field.db.type === 'jsonb') {
            columnOptions.type = 'jsonb';
          } else if (field.db.type === 'array') {
            columnOptions.type = 'array';
          } else if (field.db.type === 'uuid') {
            columnOptions.type = 'uuid';
          }
          break;
        case 'mysql':
          // MySQL 特定类型
          if (field.db.type === 'jsonb') {
            columnOptions.type = 'json';
          } else if (field.db.type === 'array') {
            columnOptions.type = 'simple-array';
          } else if (field.db.type === 'uuid') {
            columnOptions.type = 'varchar';
            columnOptions.length = 36;
          }
          break;
        case 'mongodb':
          // MongoDB 特定类型
          if (field.db.type === 'jsonb' || field.db.type === 'json') {
            columnOptions.type = 'mixed';
          } else if (field.db.type === 'array') {
            columnOptions.type = 'array';
          } else if (field.db.type === 'uuid') {
            columnOptions.type = 'string';
          }
          break;
      }

      // 通用类型
      if (!columnOptions.type) {
        columnOptions.type = field.db.type;
      }
    }

    // 处理字段长度
    if (field.db.length) {
      columnOptions.length = field.db.length;
    }

    // 处理精度和小数位数
    if (field.db.precision) {
      columnOptions.precision = field.db.precision;
    }
    if (field.db.scale) {
      columnOptions.scale = field.db.scale;
    }

    // 处理是否可为空
    if (typeof field.db.nullable === 'boolean') {
      columnOptions.nullable = field.db.nullable;
    }

    // 处理默认值
    if (field.db.default !== undefined) {
      // 检查是否是特殊的数据库函数默认值
      if ((field.db as any).defaultType === 'function' && (field.db as any).defaultFunction) {
        // 处理函数类型的默认值
        switch ((field.db as any).defaultFunction) {
          case 'CURRENT_TIMESTAMP':
            columnOptions.default = () => 'CURRENT_TIMESTAMP';
            break;
          case 'CURRENT_DATE':
            columnOptions.default = () => 'CURRENT_DATE';
            break;
          case 'CURRENT_TIME':
            columnOptions.default = () => 'CURRENT_TIME';
            break;
          case 'UUID_GENERATE':
            if (dbType === 'postgres') {
              columnOptions.default = () => 'gen_random_uuid()';
            } else if (dbType === 'mysql') {
              columnOptions.default = () => 'UUID()';
            } else {
              columnOptions.default = () => 'UUID()';
            }
            break;
          default:
            // 对于其他函数，直接使用原始值
            columnOptions.default = field.db.default;
        }
      } else {
        // 普通默认值处理
        // 检查是否是数据库函数字符串，如果是则转换为函数形式
        if (typeof field.db.default === 'string') {
          const dbFunctions = [
            'CURRENT_TIMESTAMP',
            'CURRENT_DATE',
            'CURRENT_TIME',
            'NOW()',
            'UUID()',
          ];
          if (dbFunctions.includes(field.db.default)) {
            // 将数据库函数字符串转换为函数形式
            const funcName = field.db.default === 'NOW()' ? 'CURRENT_TIMESTAMP' : field.db.default;
            columnOptions.default = () => funcName;
          } else {
            columnOptions.default = field.db.default;
          }
        } else {
          columnOptions.default = field.db.default;
        }
      }
    }

    // 处理注释
    if (field.db.comment) {
      columnOptions.comment = field.db.comment;
    }

    // 处理版本控制
    if (field.db.isVersion) {
      decorators.push(t.decorator(t.identifier('Version')));
    }

    // 处理唯一性
    if (field.db.unique) {
      const indexOptions: Record<string, any> = {
        unique: true,
      };

      // 通用选项
      if (field.db.where) indexOptions.where = field.db.where;
      if (field.db.nullFiltered) indexOptions.nullFiltered = true;

      // 数据库特定选项
      switch (dbType) {
        case 'mysql':
          if (field.db.fulltext) indexOptions.fulltext = true;
          if (field.db.parser) indexOptions.parser = field.db.parser;
          break;
        case 'postgres':
          if (field.db.spatial) indexOptions.spatial = true;
          if (field.db.concurrent) indexOptions.concurrent = true;
          break;
        case 'mongodb':
          if (field.db.sparse) indexOptions.sparse = true;
          if (field.db.background) indexOptions.background = true;
          if (field.db.expireAfterSeconds)
            indexOptions.expireAfterSeconds = field.db.expireAfterSeconds;
          break;
      }

      decorators.push(
        t.decorator(
          t.callExpression(t.identifier('Index'), [
            t.objectExpression(
              Object.entries(indexOptions).map(([key, value]) =>
                t.objectProperty(t.identifier(key), t.valueToNode(value)),
              ),
            ),
          ]),
        ),
      );
    }

    // 处理外键
    if (field.db.foreignKey) {
      const { table, column, onDelete, onUpdate } = field.db.foreignKey;
      const joinColumnOptions: Record<string, any> = {
        name: column,
        referencedColumnName: 'id',
      };

      if (onDelete) {
        joinColumnOptions.onDelete = onDelete;
      }
      if (onUpdate) {
        joinColumnOptions.onUpdate = onUpdate;
      }

      decorators.push(
        t.decorator(
          t.callExpression(t.identifier('JoinColumn'), [
            t.objectExpression(
              Object.entries(joinColumnOptions).map(([key, value]) =>
                t.objectProperty(t.identifier(key), t.valueToNode(value)),
              ),
            ),
          ]),
        ),
      );
    }

    // 处理关系
    if (field.relation) {
      const { type, target, foreignKey } = field.relation;
      const relationOptions: Record<string, any> = {
        target: () => target,
      };

      if (foreignKey) {
        relationOptions.foreignKey = foreignKey;
      }

      switch (type) {
        case 'one-to-one':
          decorators.push(
            t.decorator(
              t.callExpression(t.identifier('OneToOne'), [
                t.objectExpression(
                  Object.entries(relationOptions).map(([key, value]) =>
                    t.objectProperty(t.identifier(key), t.valueToNode(value)),
                  ),
                ),
              ]),
            ),
          );
          break;
        case 'one-to-many':
          decorators.push(
            t.decorator(
              t.callExpression(t.identifier('OneToMany'), [
                t.objectExpression(
                  Object.entries(relationOptions).map(([key, value]) =>
                    t.objectProperty(t.identifier(key), t.valueToNode(value)),
                  ),
                ),
              ]),
            ),
          );
          break;
        case 'many-to-many':
          decorators.push(
            t.decorator(
              t.callExpression(t.identifier('ManyToMany'), [
                t.objectExpression(
                  Object.entries(relationOptions).map(([key, value]) =>
                    t.objectProperty(t.identifier(key), t.valueToNode(value)),
                  ),
                ),
              ]),
            ),
          );
          break;
      }
    }

    // 添加 Column 装饰器
    decorators.push(
      t.decorator(
        t.callExpression(t.identifier('Column'), [
          t.objectExpression(
            Object.entries(columnOptions).map(([key, value]) => {
              // 特殊处理函数类型的默认值
              if (key === 'default' && typeof value === 'function') {
                // 创建箭头函数AST节点
                const funcBody = value().toString();
                const arrowFunction = t.arrowFunctionExpression([], t.stringLiteral(funcBody));
                return t.objectProperty(t.identifier(key), arrowFunction);
              }
              return t.objectProperty(t.identifier(key), t.valueToNode(value));
            }),
          ),
        ]),
      ),
    );
  }

  return decorators;
};

// 生成 TypeORM 监听器
const generateTypeOrmListener = (typeItem: ITypeEntity) => {
  if (!typeItem.access?.transformers) return null;

  const listenerClass = t.classDeclaration(
    t.identifier(`${typeItem.name}Listener`),
    null,
    t.classBody([
      // listenTo 方法
      t.classMethod(
        'method',
        t.identifier('listenTo'),
        [],
        t.blockStatement([t.returnStatement(t.identifier(typeItem.name))]),
      ),

      // beforeInsert 方法
      ...(typeItem.access.transformers.beforeWrite
        ? [
            t.classMethod(
              'method',
              t.identifier('beforeInsert'),
              [t.identifier('event')],
              t.blockStatement([
                t.expressionStatement(
                  t.callExpression(
                    t.memberExpression(t.identifier('event'), t.identifier('entity')),
                    [t.stringLiteral(typeItem.access.transformers.beforeWrite.transformer || '')],
                  ),
                ),
              ]),
            ),
          ]
        : []),

      // beforeUpdate 方法
      ...(typeItem.access.transformers.beforeWrite
        ? [
            t.classMethod(
              'method',
              t.identifier('beforeUpdate'),
              [t.identifier('event')],
              t.blockStatement([
                t.expressionStatement(
                  t.callExpression(
                    t.memberExpression(t.identifier('event'), t.identifier('entity')),
                    [t.stringLiteral(typeItem.access.transformers.beforeWrite.transformer || '')],
                  ),
                ),
              ]),
            ),
          ]
        : []),

      // afterLoad 方法
      ...(typeItem.access.transformers.afterRead
        ? [
            t.classMethod(
              'method',
              t.identifier('afterLoad'),
              [t.identifier('entity')],
              t.blockStatement([
                t.expressionStatement(
                  t.callExpression(t.identifier('entity'), [
                    t.stringLiteral(typeItem.access.transformers.afterRead.transformer || ''),
                  ]),
                ),
              ]),
            ),
          ]
        : []),
    ]),
  );

  // 修改添加 EventSubscriber 装饰器的代码
  listenerClass.decorators = [t.decorator(t.identifier('EventSubscriber'))];

  return listenerClass;
};

// 收集 TypeORM 装饰器
const collectTypeOrmDecorators = (typeItem: ITypeEntity) => {
  const decorators = new Set<string>();

  // 添加 Entity 装饰器
  if (typeItem.db) {
    decorators.add('Entity');
  }

  // 检查是否有类级别索引
  if ((typeItem.db as any)?.indexes && Array.isArray((typeItem.db as any).indexes)) {
    decorators.add('Index');
  }

  // 收集字段装饰器
  typeItem.fields?.forEach((field) => {
    if (field.db) {
      if (field.db.isPrimary) {
        if (field.db.isGenerated) {
          decorators.add('PrimaryGeneratedColumn');
        } else {
          decorators.add('PrimaryColumn');
        }
      } else {
        decorators.add('Column');
      }

      // 字段级别的索引
      if (field.db.unique || field.db.fulltext || field.db.spatial || field.db.sparse) {
        decorators.add('Index');
      }

      // 关系装饰器
      if (field.relation) {
        switch (field.relation.type) {
          case 'one-to-one':
            decorators.add('OneToOne');
            break;
          case 'one-to-many':
            decorators.add('OneToMany');
            break;
          case 'many-to-many':
            decorators.add('ManyToMany');
            break;
        }
      }

      // 外键装饰器
      if (field.db.foreignKey) {
        decorators.add('JoinColumn');
      }

      // 版本控制装饰器
      if (field.db.isVersion) {
        decorators.add('VersionColumn');
      }
    }
  });

  return Array.from(decorators);
};

export const generateDataInterface = async (
  typeItem: ITypeEntity,
  options: {
    hasDefaultValue?: boolean;
    isFileCode?: boolean;
    exportImportNames?: boolean;
    isDbMode?: boolean;
  } = {},
) => {
  voTypes = [];

  // 生成主类
  const { classDeclaration, importTypeNames, importTypeEntities } = await getClassDeclaration(
    typeItem,
    'type',
    'fields',
    typeItem?.name,
    options.hasDefaultValue,
    options.isDbMode && !!typeItem.db?.name,
  );

  // 如果是数据库模式，添加 Entity 装饰器
  if (options.isDbMode && typeItem.db?.name) {
    const entityOptions: any = {};
    if (typeItem.db.name) entityOptions.name = typeItem.db.name;
    if (typeItem.db.database) entityOptions.database = typeItem.db.database;
    // if (typeItem.db.type) entityOptions.type = typeItem.db.type;

    const decorators = [
      t.decorator(
        t.callExpression(t.identifier('Entity'), [
          t.objectExpression(
            Object.entries(entityOptions).map(([key, value]) =>
              t.objectProperty(t.identifier(key), t.valueToNode(value)),
            ),
          ),
        ]),
      ),
    ];

    // 添加类级别的索引装饰器
    if ((typeItem.db as any).indexes && Array.isArray((typeItem.db as any).indexes)) {
      (typeItem.db as any).indexes.forEach((indexInfo: any) => {
        if (indexInfo.columns && Array.isArray(indexInfo.columns)) {
          const indexArgs: (t.Expression | t.SpreadElement)[] = [
            t.arrayExpression(indexInfo.columns.map((col: string) => t.stringLiteral(col))),
          ];

          // 如果有索引选项，添加选项对象
          const indexOptions: any = {};
          if (typeof indexInfo.unique === 'boolean') indexOptions.unique = indexInfo.unique;
          if (indexInfo.name) indexOptions.name = indexInfo.name;
          if (indexInfo.where) indexOptions.where = indexInfo.where;

          if (Object.keys(indexOptions).length > 0) {
            indexArgs.push(
              t.objectExpression(
                Object.entries(indexOptions).map(([key, value]) =>
                  t.objectProperty(t.identifier(key), t.valueToNode(value)),
                ),
              ),
            );
          }

          decorators.push(t.decorator(t.callExpression(t.identifier('Index'), indexArgs)));
        }
      });
    }

    classDeclaration.decorators = decorators;
  }

  // 生成监听器类
  const listenerClass =
    options.isDbMode && typeItem.db?.name ? generateTypeOrmListener(typeItem) : null;

  // 生成代码
  const program = listenerClass
    ? t.program([classDeclaration, listenerClass])
    : t.program([classDeclaration]);

  const { code } = generate(program, {
    comments: true, // 启用注释输出
    compact: false, // 不压缩代码，保持可读性
    retainLines: false, // 不保留原始行号
    jsescOption: {
      minimal: true,
    },
  });

  let _code = code.replaceAll(': ?', '?: ');

  logger('生成的原始代码:');
  logger(_code);

  // 处理特殊的函数签名类型
  // 查找所有标记了 _rawTypeString 的字段，进行字符串替换
  const fieldsWithRawType = typeItem.fields?.filter((field) => (field as any)._rawTypeString) || [];
  logger(
    '需要处理的特殊函数字段:',
    fieldsWithRawType.map((f) => ({
      name: f.name,
      required: f.required,
      _rawTypeString: (f as any)._rawTypeString,
      _isOptional: (f as any)._isOptional,
    })),
  );

  fieldsWithRawType.forEach((field) => {
    const fieldName = field.name;
    const rawTypeString = (field as any)._rawTypeString;
    const isOptional = (field as any)._isOptional;

    // 查找并替换字段的类型注解
    // 匹配模式：fieldName: any; 或 fieldName;
    let finalTypeString = rawTypeString;

    // 构建正则表达式，匹配字段声明
    // 匹配: "  fieldName: any;" 或 "  fieldName;" 或 "  fieldName?: any;"
    const fieldPattern = new RegExp(`(\\s+${fieldName})\\??\\s*:\\s*[^;]+;`, 'g');
    const fieldPatternNoType = new RegExp(`(\\s+${fieldName})\\??\\s*;`, 'g');

    // 如果字段是可选的，添加可选标记
    if (isOptional) {
      // 将 fieldName: type; 改为 fieldName?: type;
      const replacement = `$1?: ${finalTypeString};`;
      if (_code.match(fieldPattern)) {
        _code = _code.replace(fieldPattern, replacement);
      } else if (_code.match(fieldPatternNoType)) {
        _code = _code.replace(fieldPatternNoType, replacement);
      }
    } else {
      // 正常替换
      const replacement = `$1: ${finalTypeString};`;
      if (_code.match(fieldPattern)) {
        _code = _code.replace(fieldPattern, replacement);
      } else if (_code.match(fieldPatternNoType)) {
        _code = _code.replace(fieldPatternNoType, replacement);
      }
    }

    logger(
      `替换字段 ${fieldName} 的类型为: ${finalTypeString}${isOptional ? ' (可选)' : ' (必需)'}`,
    );
    logger(`字段 ${fieldName} 是否可选: ${isOptional}, 原始字段 required: ${field.required}`);
  });

  // 生成丰富的 JSDoc 元数据注释
  const metaComment = generateTypeEntityMetaComment(typeItem);

  // 修改文件代码生成逻辑，使用字符串替换添加 export
  const fileCode = `${metaComment}
${_code.replace(`class ${typeItem.name}`, `export class ${typeItem.name}`)}`;

  if (options.exportImportNames) {
    return {
      code: fileCode,
      importTypeNames,
      importTypeEntities,
    };
  }

  if (options.isFileCode) {
    // logger('importTypeNames: ', importTypeNames);
    // logger('importTypeEntities: ', importTypeEntities);

    // 收集并生成 TypeORM 导入
    const typeOrmDecorators =
      options.isDbMode && typeItem.db?.name ? collectTypeOrmDecorators(typeItem) : [];
    const typeOrmImport =
      typeOrmDecorators.length > 0
        ? `import { ${typeOrmDecorators.join(', ')} } from 'typeorm';\n`
        : '';

    // 生成其他导入
    const importCode = importTypeEntities
      .map((entity) => `import { ${entity.name} } from '@${getFileLocalPath(entity)}';`)
      .join('\n');

    return `${typeOrmImport}${importCode}${importCode ? '\n' : ''}${fileCode}`;
  }

  return _code;
};

export const generateTypeFile = async (projectId: string) => {
  const codes: {
    typeName: string;
    typeDesc: string;
    typeFolder?: string;
    typeFolderPath?: string;
    code: string;
  }[] = [];
  const types = await getTypeByParams(
    {
      type: 'vo',
    },
    projectId,
  );

  for (const typeItem of types) {
    const code = await generateDataInterface(typeItem);
    codes.push({
      typeName: typeItem.name,
      typeDesc: typeItem.desc,
      typeFolder: typeItem?.folder || '/types',
      typeFolderPath: typeItem?.folderPath || '/types',
      code,
    });
  }
  return codes;
};

// @ts-ignore
window.generateTypeFile = generateTypeFile;

/**
 * 根据数据类型生成Class
 */
export const getClassDeclaration = async (
  typeItem: ITypeEntity,
  mode: 'store' | 'type',
  field = 'fields',
  typeName: string,
  hasDefaultValue = true,
  isDbMode?: boolean,
) => {
  const { classProperties, importTypeNames, importTypeEntities } = await fieldsToClassProperty(
    typeItem,
    mode === 'type',
    field,
    false,
    hasDefaultValue,
  );
  const classDeclaration = t.classDeclaration(
    t.identifier(typeName), // changeCase.pascalCase(typeName)
    undefined,
    t.classBody(classProperties),
  );
  return {
    classDeclaration,
    importTypeNames,
    importTypeEntities,
  };
};

/**
 * 根据数据类型生成Class成员变量
 */
/**
 * 处理字符串类型字段
 */
const handleStringField = (
  field: ITypeEntityField,
): { value: t.Expression; typeAnnotation: t.TypeAnnotation } => {
  const defaultValue = transformFieldValue(field);
  const value =
    field.required && !defaultValue
      ? t.stringLiteral('')
      : t.stringLiteral(String(defaultValue || ''));

  const typeAnnotation = t.typeAnnotation(
    field.isArray ? t.arrayTypeAnnotation(t.stringTypeAnnotation()) : t.stringTypeAnnotation(),
  );

  return { value: field.isArray ? t.arrayExpression([]) : value, typeAnnotation };
};

/**
 * 处理数字类型字段
 */
const handleNumberField = (
  field: ITypeEntityField,
): { value: t.Expression; typeAnnotation: t.TypeAnnotation } => {
  const defaultValue = transformFieldValue(field);
  const value =
    defaultValue !== undefined && defaultValue !== null
      ? Number.isNaN(Number(defaultValue))
        ? t.nullLiteral()
        : t.numericLiteral(Number(defaultValue))
      : undefined;

  const typeAnnotation = t.typeAnnotation(
    field.isArray ? t.arrayTypeAnnotation(t.numberTypeAnnotation()) : t.numberTypeAnnotation(),
  );

  return { value: field.isArray ? t.arrayExpression([]) : value, typeAnnotation };
};

/**
 * 处理布尔类型字段
 */
const handleBooleanField = (
  field: ITypeEntityField,
): { value: t.Expression; typeAnnotation: t.TypeAnnotation } => {
  const defaultValue = transformFieldValue(field);
  const value =
    typeof defaultValue === 'boolean' || field.required
      ? t.booleanLiteral(Boolean(defaultValue))
      : undefined;

  const typeAnnotation = t.typeAnnotation(
    field.isArray ? t.arrayTypeAnnotation(t.booleanTypeAnnotation()) : t.booleanTypeAnnotation(),
  );

  return { value: field.isArray ? t.arrayExpression([]) : value, typeAnnotation };
};

/**
 * 处理引用类型字段
 */
const handleImportField = async (
  field: ITypeEntityField,
  typeItem: ITypeEntity,
  importTypeNames: string[],
  importTypeEntities: ITypeEntity[],
): Promise<{ value: t.Expression; typeAnnotation: t.TypeAnnotation }> => {
  let importTypeName = field.importEntity?.name;
  if (!field.importEntity) {
    if (field.import === typeItem._id) {
      importTypeName = typeItem.name;
    } else if (field.import) {
      if (field.import !== 'Partial') {
        // 处理遗留问题
        importTypeName = 'any';
      } else {
        const importedType = await getTypeById(field.import);
        if (importedType?._id) {
          importTypeName = importedType.name;
          field.importEntity = importedType;
        } else {
          console.warn('字段引用模型错误:', 'field: ', field, 'typeItem: ', typeItem);
          importTypeName = 'any';
        }
      }
    } else {
      // 如果 field.import 为空或 undefined，说明这是一个没有具体类型的对象字段
      console.warn('字段没有 import 信息，将使用 any 类型:', field.name);
      importTypeName = 'any';
    }
  }

  if (importTypeName === 'any') {
    return {
      value: t.objectExpression([]),
      typeAnnotation: t.typeAnnotation(
        field.isArray ? t.arrayTypeAnnotation(t.anyTypeAnnotation()) : t.anyTypeAnnotation(),
      ),
    };
  }

  const itemTypeAnnotation = t.genericTypeAnnotation(
    t.identifier('Partial'),
    t.typeParameterInstantiation([t.genericTypeAnnotation(t.identifier(importTypeName))]),
  );

  if (field.importEntity) {
    const res = await getClassDeclaration(field.importEntity, 'type', 'fields', importTypeName);
    voTypes.push(t.exportNamedDeclaration(res.classDeclaration));
  }
  if (importTypeName && importTypeName !== 'any') {
    importTypeNames.push(importTypeName);
    importTypeEntities.push(field.importEntity);
  }

  const defaultValue = transformFieldValue(field);
  const value = field.isArray
    ? t.arrayExpression([])
    : typeof defaultValue === 'object' && defaultValue !== null
    ? t.objectExpression(
        Object.entries(defaultValue).map(([key, val]) =>
          t.objectProperty(t.identifier(key), t.valueToNode(val)),
        ),
      )
    : t.objectExpression([]);

  return {
    value,
    typeAnnotation: t.typeAnnotation(
      field.isArray ? t.arrayTypeAnnotation(itemTypeAnnotation) : itemTypeAnnotation,
    ),
  };
};

/**
 * 处理对象类型字段
 */
const handleObjectField = async (
  field: ITypeEntityField,
): Promise<{ value: t.Expression; typeAnnotation: t.TypeAnnotation }> => {
  if (field.fields?.length > 0) {
    const objectTypeProps = (
      await fieldsToClassProperty(
        {
          name: field.name,
          desc: field.desc,
          type: 'vo',
          fields: field.fields,
        },
        true,
        'fields',
        true,
      )
    ).objectProperties;

    const objectType = t.objectTypeAnnotation(objectTypeProps);

    const defaultValue = transformFieldValue(field);
    const value = field.isArray
      ? t.arrayExpression([])
      : typeof defaultValue === 'object' && defaultValue !== null
      ? t.objectExpression(
          Object.entries(defaultValue).map(([key, val]) =>
            t.objectProperty(t.identifier(key), t.valueToNode(val)),
          ),
        )
      : t.objectExpression([]);

    return {
      value,
      typeAnnotation: t.typeAnnotation(
        field.isArray ? t.arrayTypeAnnotation(objectType) : objectType,
      ),
    };
  }

  const defaultValue = transformFieldValue(field);
  const value = field.isArray
    ? t.arrayExpression([])
    : typeof defaultValue === 'object' && defaultValue !== null
    ? t.objectExpression(
        Object.entries(defaultValue).map(([key, val]) =>
          t.objectProperty(t.identifier(key), t.valueToNode(val)),
        ),
      )
    : t.objectExpression([]);
  return {
    value,
    typeAnnotation: t.typeAnnotation(t.anyTypeAnnotation()),
  };
};

const handleFunctionField = (
  field: ITypeEntityField,
): { value: t.Expression; typeAnnotation: t.TypeAnnotation } => {
  // 默认值：空函数或undefined（根据是否可选）
  const value = field.isArray
    ? t.arrayExpression([])
    : field.required
    ? t.arrowFunctionExpression([], t.blockStatement([]))
    : t.identifier('undefined');

  // 尝试从 setterProps.template 中解析函数签名
  let functionType = t.genericTypeAnnotation(t.identifier('Function'));
  let canGenerateSpecificType = false;

  if (field.setterProps) {
    let setterProps = field.setterProps;

    // 如果 setterProps 是字符串，尝试解析
    if (typeof setterProps === 'string') {
      try {
        setterProps = JSON.parse(setterProps);
      } catch (e) {
        // 解析失败，使用默认类型
      }
    }

    // 如果有 template，尝试解析函数签名
    if (setterProps && typeof setterProps === 'object' && setterProps.template) {
      const template = setterProps.template;
      const paramMatch = template.match(/\(([^)]*)\)/);

      if (paramMatch && paramMatch[1]) {
        const paramList = paramMatch[1].trim();
        logger(`函数字段 ${field.name} 的参数信息:`, paramList);

        // 如果参数不是默认的 'e'，标记可以生成具体的函数类型
        if (paramList && paramList !== 'e') {
          // 不在这里生成复杂的 AST，而是标记字段，让后续处理
          canGenerateSpecificType = true;
          (field as any)._functionSignature = `(${paramList}) => void`;
          logger(`为函数字段 ${field.name} 标记具体类型签名:`, `(${paramList}) => void`);
        }
      }
    }
  }

  // 如果成功生成了具体的函数类型，标记字段可以省略 @Form 装饰器
  if (canGenerateSpecificType) {
    (field as any)._canOmitFormDecorator = true;
  }

  return {
    value,
    typeAnnotation: t.typeAnnotation(
      field.isArray ? t.arrayTypeAnnotation(functionType) : functionType,
    ),
  };
};

/**
 * 生成字段注释内容，包含描述和示例
 */
const generateFieldComment = (field: ITypeEntityField): string => {
  const parts: string[] = [];

  // 添加描述
  if (field.desc) {
    parts.push(field.desc);
  }

  // 添加示例，使用特定格式
  if (field.example !== undefined && field.example !== null && field.example !== '') {
    const exampleStr =
      typeof field.example === 'object' ? JSON.stringify(field.example) : String(field.example);
    parts.push(`@example ${exampleStr}`);
  }

  return parts.join(' ');
};

/**
 * 创建节点属性
 */
const createPropertyNode = async (
  field: ITypeEntityField,
  value: t.Expression,
  typeAnnotation: t.TypeAnnotation,
  isObjectType: boolean,
  onlyType?: boolean,
  isDbMode?: boolean,
  dbType?: string,
) => {
  if (isObjectType) {
    const node = t.objectTypeProperty(t.identifier(field.name), typeAnnotation.typeAnnotation);
    const commentText = generateFieldComment(field);
    if (commentText) t.addComment(node, 'leading', ` ${commentText} `, false);
    return node;
  }

  const decorators = [];

  // 判断是否是默认的 setter
  const getDefaultSetter = (fieldType: string): string => {
    switch (fieldType) {
      case 'string':
        return 'StringSetter';
      case 'number':
        return 'NumberSetter';
      case 'boolean':
        return 'BoolSetter';
      case 'object':
        return 'JsonSetter';
      case 'function':
        return 'FunctionSetter';
      case 'Date':
        return 'DatePicker';
      default:
        return 'StringSetter';
    }
  };

  const isDefaultSetter = (fieldType: string, setter: string): boolean => {
    return getDefaultSetter(fieldType) === setter;
  };

  // 添加 Form 装饰器（用于 IProps 字段的 setter 配置）
  // 只有在非默认配置时才生成装饰器
  if (field.setter || field.setterProps) {
    const formOptions: any = {};
    let needsDecorator = false;

    // 检查 setter 是否需要显式声明
    if (field.setter && !isDefaultSetter(field.type, field.setter)) {
      formOptions.setter = field.setter;
      needsDecorator = true;
    }

    // 检查 setterProps 是否存在
    if (field.setterProps) {
      // 如果 setterProps 是字符串，尝试解析为对象
      if (typeof field.setterProps === 'string') {
        try {
          formOptions.setterProps = JSON.parse(field.setterProps);
        } catch (e) {
          // 如果解析失败，包装为对象
          formOptions.setterProps = { template: field.setterProps };
        }
      } else {
        // 如果已经是对象，直接使用
        formOptions.setterProps = field.setterProps;
      }
      needsDecorator = true;
    }

    // 对于函数类型，如果只有默认的 template，也不需要装饰器
    if (
      field.type === 'function' &&
      formOptions.setterProps &&
      Object.keys(formOptions.setterProps).length === 1 &&
      formOptions.setterProps.template === `${field.name}(e){}` &&
      !formOptions.setter
    ) {
      needsDecorator = false;
    }

    // 如果函数类型已经生成了具体的类型签名，也不需要装饰器
    if (field.type === 'function' && (field as any)._canOmitFormDecorator) {
      needsDecorator = false;
    }

    // 只有在需要时才生成装饰器
    if (needsDecorator && Object.keys(formOptions).length > 0) {
      const formOptionsObj = t.objectExpression(
        Object.entries(formOptions).map(([key, value]) => {
          // 对于 setterProps 对象，需要递归处理
          if (key === 'setterProps' && typeof value === 'object' && value !== null) {
            const setterPropsObj = t.objectExpression(
              Object.entries(value).map(([propKey, propValue]) =>
                t.objectProperty(t.identifier(propKey), t.valueToNode(propValue)),
              ),
            );
            return t.objectProperty(t.identifier(key), setterPropsObj);
          }
          return t.objectProperty(t.identifier(key), t.valueToNode(value));
        }),
      );

      decorators.push(t.decorator(t.callExpression(t.identifier('Form'), [formOptionsObj])));
    }
  }

  // 添加 TypeORM 装饰器
  if (isDbMode) {
    decorators.push(...generateTypeOrmDecorator(field, dbType));
  } else {
    // 原有的装饰器逻辑
    if (!onlyType) {
      decorators.push(t.decorator(t.identifier('observable')));
    }
  }

  if (field.isApi && field.apiOptions) {
    if (typeof field?.isInit === 'boolean') (field.apiOptions as any).isInit = field?.isInit;
    if (typeof field?.isSync === 'boolean') (field.apiOptions as any).isSync = field?.isSync;
    if (typeof field?.apiImport === 'string' && field?.apiImport) {
      (field.apiOptions as any).api = field?.apiImport;
      if (field?.apiImportEntity) {
        (field.apiOptions as any).api = field?.apiImportEntity?.uri;
      } else {
        const typeItem = await getTypeById(field.apiImport);
        if (typeItem) {
          (field.apiOptions as any).api = typeItem.uri;
        } else {
          console.warn('API TypeItem not found 需要完成加载远程资源', field?.apiImport);
        }
      }
    }
    const apiOptionsObj = t.objectExpression(
      Object.entries(field.apiOptions)
        .filter(([key]) => !['debugState'].includes(key))
        .map(([key, value]) => {
          const processValue = (val: any): t.Expression => {
            if (typeof val === 'object' && val !== null) {
              if (val.type === 'JSExpression') {
                return t.identifier(val.value);
              }
              if (val.type === 'JSFunction') {
                const funcBody = val.value.trim();
                if (funcBody.startsWith('function')) {
                  const funcMatch = funcBody.match(/^function\s*\(([^)]*)\)\s*{([\s\S]+)}\s*$/);
                  if (funcMatch && funcMatch[2]) {
                    return t.identifier(funcMatch[2].trim());
                  }
                }
                return t.identifier(funcBody.replace('function dataHandler(res) ', '(res) => '));
              }
              // 处理嵌套对象
              if (Array.isArray(val)) {
                return t.arrayExpression(val.map((item) => processValue(item)));
              }
              return t.objectExpression(
                Object.entries(val).map(([k, v]) =>
                  t.objectProperty(t.identifier(k), processValue(v)),
                ),
              );
            }
            return typeof val === 'string' ? t.stringLiteral(val) : t.valueToNode(val);
          };

          return t.objectProperty(t.identifier(key), processValue(value));
        }),
    );
    decorators.push(t.decorator(t.callExpression(t.identifier('DataSource'), [apiOptionsObj])));
  }

  // 处理特殊的函数签名类型注解
  let finalTypeAnnotation = typeAnnotation;
  if (
    typeAnnotation &&
    (typeAnnotation as any).typeAnnotation &&
    (typeAnnotation as any).typeAnnotation._isFunctionSignature
  ) {
    const functionSignature = (typeAnnotation as any).typeAnnotation.value;
    logger(`使用自定义函数签名: ${functionSignature}`);

    // 直接使用字符串创建类型注解，避免复杂的 AST 构建
    finalTypeAnnotation = null; // 先设为 null，后续通过字符串替换处理
    (field as any)._rawTypeString = functionSignature;
  }

  const node = t.classProperty(t.identifier(field.name), value, finalTypeAnnotation, decorators);
  const commentText = generateFieldComment(field);
  if (commentText) t.addComment(node, 'leading', ` ${commentText} `, false);
  return node;
};

/**
 * 处理字段类型转换为Class属性
 */
export const fieldsToClassProperty = async (
  typeItem: ITypeEntity,
  onlyType?: boolean,
  field = 'fields',
  isObjectType?: boolean,
  hasDefaultValue = true,
) => {
  const classProperties: t.ClassProperty[] = [];
  const objectProperties: t.ObjectTypeProperty[] = [];
  const importTypeNames: string[] = [];
  const importTypeEntities: ITypeEntity[] = [];
  const voTypeFields = typeItem?.[field];

  if (voTypeFields && voTypeFields.length > 0) {
    for (const field of voTypeFields) {
      let result: { value: t.Expression; typeAnnotation: t.TypeAnnotation };

      switch (field.type) {
        case 'string':
          result = handleStringField(field);
          break;
        case 'number':
          result = handleNumberField(field);
          break;
        case 'boolean':
          result = handleBooleanField(field);
          break;
        case 'Date':
          result = {
            value: field.isArray ? t.arrayExpression([]) : t.identifier('new Date()'),
            typeAnnotation: t.typeAnnotation(
              field.isArray
                ? t.arrayTypeAnnotation(t.genericTypeAnnotation(t.identifier('Date')))
                : t.genericTypeAnnotation(t.identifier('Date')),
            ),
          };
          break;
        case 'object':
          result = field.import
            ? await handleImportField(field, typeItem, importTypeNames, importTypeEntities)
            : await handleObjectField(field);
          break;
        case 'function':
          result = handleFunctionField(field);

          // 如果有自定义的函数签名，使用字符串形式的类型注解
          if ((field as any)._functionSignature) {
            const functionSignature = (field as any)._functionSignature;
            // 创建一个特殊的类型注解，使用字符串表示
            result.typeAnnotation = {
              type: 'TypeAnnotation',
              typeAnnotation: {
                type: 'StringLiteral', // 临时使用，后续会被特殊处理
                value: functionSignature,
                _isFunctionSignature: true,
              },
            } as any;
          }
          break;
        default:
          result = {
            value: t.objectExpression([]),
            typeAnnotation: t.typeAnnotation(
              field.isArray ? t.arrayTypeAnnotation(t.anyTypeAnnotation()) : t.anyTypeAnnotation(),
            ),
          };
      }

      if (!field.required) {
        // 检查是否是特殊的函数签名类型，如果是，跳过 nullable 处理
        const isSpecialFunctionType =
          result.typeAnnotation &&
          (result.typeAnnotation as any).typeAnnotation &&
          (result.typeAnnotation as any).typeAnnotation._isFunctionSignature;

        if (!isSpecialFunctionType) {
          const innerType = field.isArray
            ? t.arrayTypeAnnotation(
                result.typeAnnotation.typeAnnotation.type === 'ArrayTypeAnnotation'
                  ? (result.typeAnnotation.typeAnnotation as any).elementType
                  : result.typeAnnotation.typeAnnotation,
              )
            : result.typeAnnotation.typeAnnotation;

          result.typeAnnotation = t.typeAnnotation(t.nullableTypeAnnotation(innerType));
        } else {
          // 对于特殊函数类型，在字符串替换时处理可选性
          (field as any)._isOptional = true;
        }
      }
      if (field.isArray) {
        // logger('node: ', result.typeAnnotation);
      }
      // logger('field: ', field);
      // logger('result: ', result);
      const node = await createPropertyNode(
        field,
        hasDefaultValue ? result.value : undefined,
        result.typeAnnotation,
        isObjectType,
        onlyType,
        typeItem.db ? true : false,
        typeItem.db?.type,
      );
      if (isObjectType) {
        objectProperties.push(node as t.ObjectTypeProperty);
      } else {
        classProperties.push(node as t.ClassProperty);
      }
    }
  }

  return {
    classProperties,
    objectProperties,
    importTypeNames,
    importTypeEntities,
  };
};
